package com.lzj.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lzj.common.core.domain.PageQuery;
import com.lzj.common.core.domain.entity.SysDictData;
import com.lzj.common.core.page.TableDataInfo;
import com.lzj.common.utils.StringUtils;
import com.lzj.system.domain.SysComQuery;
import com.lzj.system.domain.bo.SysComQueryBo;
import com.lzj.system.domain.vo.SysComQueryVo;
import com.lzj.system.mapper.SysComQueryMapper;
import com.lzj.system.service.ISysComQueryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 通用查询Service业务层处理
 *
 * @author lzj
 * @date 2024-10-18
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SysComQueryServiceImpl implements ISysComQueryService {

    private final SysComQueryMapper baseMapper;

    private static final String PT_LEFT = "#{";
    private static final String PT_RIGHT = "}";

    /**
     * 查询通用查询
     */
    @Override
    public SysComQueryVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询通用查询列表
     */
    @Override
    public TableDataInfo<SysComQueryVo> queryPageList(SysComQueryBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysComQuery> lqw = buildQueryWrapper(bo);
        Page<SysComQueryVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询通用查询列表
     */
    @Override
    public List<SysComQueryVo> queryList(SysComQueryBo bo) {
        LambdaQueryWrapper<SysComQuery> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysComQuery> buildQueryWrapper(SysComQueryBo bo) {
        //Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysComQuery> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getName()), SysComQuery::getName, bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getCode()), SysComQuery::getCode, bo.getCode());
        return lqw;
    }

    /**
     * 新增通用查询
     */
    @Override
    public Boolean insertByBo(SysComQueryBo bo) {
        SysComQuery add = BeanUtil.toBean(bo, SysComQuery.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改通用查询
     */
    @Override
    public Boolean updateByBo(SysComQueryBo bo) {
        SysComQuery update = BeanUtil.toBean(bo, SysComQuery.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysComQuery entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除通用查询
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 测试查询数据
     * 
     * @return List<SysDictData>
     */
    @Override
    public List<SysDictData> selectQueryData(SysComQueryBo bo) {
        String sql = bo.getCustomSql();
        String ftSql = formatSql(sql, bo.getParams());
        bo.setCustomSql(ftSql);
        return baseMapper.selectQueryData(bo);
    }

    /**
     * 替换sql参数
     *
     * @param sql 查询sql, 以#{}作为占位符
     * @param params 参数
     * @return  处理后的SQL
     */
    private String formatSql(String sql, Map<String, Object> params) {
        String ftSql = sql;
        for (String key : params.keySet()) {
            Object val = params.get(key);
            String pattern = PT_LEFT + key + PT_RIGHT;
            if (val instanceof String) {
                String place = "\'" + val + "\'";
                ftSql = StringUtils.replace(ftSql, pattern, place);
            }
            else if (val instanceof Long || val instanceof Integer) {
                String place = String.valueOf(val);
                ftSql = StringUtils.replace(ftSql, pattern, place);
            } 
            else {
                log.error("替换通用查询sql参数{}发生错误：目前只支持字符串类型和整形参数", key);
            }
        }
        return ftSql;
    }

    /**
     * 查询所有数据
     */
    @Override
    public List<SysComQueryVo> selectAllList() {
        return baseMapper.selectVoList(null);
    }
    
}
